<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>设备终端管理</title>
	<link rel="stylesheet" href="/resource/css/common.css">
	<link rel="stylesheet" href="/resource/css/layui.css">
	<link rel="stylesheet" href="/resource/css/system.css">

</head>
<body>
<div class="layui-container">
	<div class="layui-row  layui-col-space10 flexC">
		<div class="layui-col-md3">
			<p>设备总量(台)</p>
			<p id="deviceAllp">0</p>
		</div>
		<div class="layui-col-md3">
			<p>已卖出量(台)</p>
			<p id="saleCount">0</p>
		</div>
		<div class="layui-col-md3">
			<p>今日卖出(台)</p>
			<p id="todaySale">0</p>
		</div>
		<div class="layui-col-md3">
			<p>当前在线(台)</p>
			<p id="onlinNow">0</p>
		</div>
	</div>
</div>
<div class="eData clearfix termi">
	<div class="echartsCss main6" style="width:98%;height: 500px;">
		<h3 class="summaryH3">终端设备分析</h3>
		<p class="timeTab" id="tab3">
			<span id="today3" data-id="today">今日</span>
			<span id="sevenday3" data-id="sevenday">7日</span>
			<span id="threetyday3" data-id="threetyday">30日</span>
			<span id="nintyday3" data-id="nintyday">90日</span>
		</p>
		<div id="main6" style="width: 100%;height:400px;"></div>
	</div>
</div>

<div class="eData clearfix">
	<table id="table1" class="canScroll" lay-filter="test"></table>
	<table id="table2" class="canScroll" lay-filter="test2"></table>
</div>
<div class="formHead">
	<div class="layui-form terminal changelabelWidth">
		<!--<div class="layui-form-item">-->
		<div class="layui-inline">
			<select name="sell" id="sellingEquip"><!--lay-ignore 可去掉layui样式-->
				<option value="">全部设备</option>
				<option value="1">已卖出</option>
				<option value="0">库存</option>
			</select>
		</div>
		<div class="layui-inline">
			<select name="theZone" id="theZone"></select>
		</div>
		<div class="layui-inline">
			<select name="theZoneDepot" id="theZoneDepot">
			</select>
		</div>
		<div class="layui-inline">
			<label class="layui-form-label">卖出时间</label>
			<div class="layui-input-inline">
				<input type="text" name="outStartTime" id="startTime" class="layui-input"/>
			</div>
			<div class="layui-input-inline">
				<input type="text" name="outEndTime" id="endTime" class="layui-input"/>
			</div>
		</div>
		<div class="layui-inline">
			<label class="layui-form-label">IMEI号码</label>
			<div class="layui-input-inline">
				<input type="text" name="imeiNum" id="imeiNum"  class="layui-input">
			</div>
		</div>
		<div class="layui-inline">
			<button class="layui-btn layui-btn-normal" lay-submit lay-filter="selectDevice">查询</button>
		</div>
		<!--</div>-->
	</div>
</div>
<table class="layui-hide layui-table" id="devicetable" lay-filter="devicetable"></table>
<script type="text/html" id="barDemo">
	<a class="layui-btn layui-btn-mini" lay-event="edit">编辑</a>
	{{# if(d.isRun == '0'){ }}
	<a class="layui-btn layui-btn-normal" lay-event="open">启用</a>
	{{# }else{ }}
	<a class="layui-btn layui-btn-warm" lay-event="stop">停用</a>
	{{# } }}
	<!--<a class="layui-btn layui-btn-danger layui-btn-mini" lay-event="del">删除</a>-->
</script>
<script src="/resource/jquery.min.js"></script>
<script src="/resource/layui.js"></script>
<script src="/resource/echarts.js"></script>
<script src="/resource/iframe.js"></script>
<script type="text/javascript">
    var token=(new parent.window._user()).getData('token');

    //点击获取今日、7、30、90天的时间/日期
    $(function(){
        var x = 1;
        $(".timeTab").on("click","span",function(){
            x = '';
            var _this = $(this);
            var _id = _this.attr("data-id");
            var i;
            if(_id == 'today'){
                i = 24;
                x = 1;
            }else if(_id == "sevenday"){
                i = 7;
                x = 0;
            }else if(_id == "threetyday"){
                i = 30;
                x = 2;
            }else if(_id == "nintyday"){
                i = 90;
                x = 9;
            }
            numday(i,x)
        })
        function numday(i,x){
            var timeer=[];
            if(i == "24"){
                for(var sec = 1;sec < i + 1;sec++){
                    timeer.push(sec+"时");
                }
                i = '';

            }else{
                for(var tt=1;tt<i+1;tt++){
                    var date= new Date();
                    var newDate = new Date(date.getTime() - tt*24*60*60*1000);
                    var month = newDate.getMonth()+1;
                    month<10?month='0'+month:month;
                    var date = newDate.getDate();
                    date<10?date='0'+date:date;
                    var time = newDate.getFullYear()+"-"+(month)+"-"+date;
                    timeer.push(time);
                }
            }
            var data = i+"+"+timeer+"+"+x;
//			if(par == "tab1"){

            deviceChatLine(data)
//			}else if(par == "tab2"){
//				deviceChatLine2(i+"+"+timeer)
//			}
        }
        var i = 24;
        var timeer = [];
        for(var sec = 1;sec < i + 1;sec++){
            timeer.push(sec+"时");
        }
        deviceChatLine(''+"+"+timeer+"+"+x);
    })

    function deviceChatLine(day){
        var dayNum = day.split("+");
        var d = dayNum[0];

        var dd = dayNum[1].split(",");
        var ax = parseInt(dayNum[2]);
        var daydate = [];
        daydate.push(dd)
        if(d !== ''){
            d = parseInt(d);
            daydate = daydate[0].reverse();

        }else{
            daydate = daydate[0]
        }
        $.ajax({
            type:"get",
            data:{
                "companyCode":(new parent.window._user()).getData('venderCode'), //厂商编号
                "productCode":(new parent.window._user()).getData('productCode'),  //产品名称编号
                "modelNumber":(new parent.window._user()).getData('versionCode'),//产品型号
                "_token":(new parent.window._user()).getData('token'),
                "day":d
            },
            url:"/store/deviceChatLine",
            success:function(result){
                var optionData = result.data;
                var outarr;
                var allarr ;
                var onlinearr;
                if(d == ''){
                    outarr = new Array(24);
                    outarr.fill(0);
                    $.each(optionData.deviceOutList,function(index, item){
                        outarr.splice(index,index+1,item.outDeviceNum);
                    });
                    console.log("已卖出设备："+ outarr);
                    allarr = new Array(24);
                    allarr.fill(0);
                    $.each(optionData.deviceAllList,function(index,item){
                        allarr.splice(index,index+1,item.allDeviceNum);
                    })
                    console.log("所有设备："+ allarr);
                    onlinearr = new Array(24);
                    onlinearr.fill(0);
                    $.each(optionData.deviceOnlineList,function(index,item){
                        onlinearr.splice(index,index+1,item.deviceOnlineCount);
                    })
                    console.log("在线设备："+ onlinearr);
                }else {
                    outarr = new Array(d);
                    outarr.fill(0)
                    for(var i = 0;i<daydate.length;i++){
                        for(var j = 0;j<optionData.deviceOutList.length;j++){
                            var objOut = optionData.deviceOutList[j];
                            if(objOut.outTime.substr(0,10) == daydate[i]){
                                outarr.splice(i,i+1,objOut.outDeviceNum);
                            }
                        }
                    }
                    console.log("已卖出设备："+ outarr);
                    allarr = new Array(d);
                    allarr.fill(0);
                    for(var i = 0;i<daydate.length;i++){
                        for(var j = 0;j<optionData.deviceAllList.length;j++){
                            var objAll = optionData.deviceAllList[j];
                            if(objAll.inTime.substr(0,10) == daydate[i]){
                                allarr.splice(i,i+1,objAll.allDeviceNum);
                            }
                        }
                    }
                    console.log("所有设备："+ allarr);
                    onlinearr = new Array(d);
                    onlinearr.fill(0);
                    for(var i = 0;i<daydate;i++){
                        for(var j = 0;j<optionData.deviceOnlineList.length;j++){
                            var objOnline = optionData.deviceOnlineList[j]
                            if(objOnline.createTime.substr(0,10) == daydate[i]){
                                onlinearr.splice(i,i+1,objOnline.deviceOnlineCount);
                            }
                        }
                    }
                    console.log("在线设备："+ onlinearr);
                }
                initDeviceChat(daydate,ax,outarr,allarr,onlinearr)
                /*initDeviceChat(
                    optionData.deviceOutList,
					optionData.deviceAllList,
					optionData.deviceOnlineList);*/
            }
        })
    }

    function initDeviceChat(daydate,ax,outarr,allarr,onlinearr){
        var dom6 = document.getElementById("main6");
        var myChart6 = echarts.init(dom6);
        option6 = null;
        option6 = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data:['在线设备','已卖出量','设备总量']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    dataView: {show: true, readOnly: false},
                    magicType: {show: true, type: ['line', 'bar']},
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },

            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: daydate,
                axisLabel:{
                    interval:ax,
                }
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name:'在线设备',
                    type:'line',
                    data:onlinearr
                },
                {
                    name:'已卖出量',
                    type:'line',
                    data:outarr
                },
                {
                    name:'设备总量',
                    type:'line',
                    data:allarr
                }
            ]
        };
        if (option6 && typeof option6 === "object") {
            myChart6.setOption(option6, true);
        }
        window.onresize = function(){
            myChart6.resize();
        }
    }



    var where={
        "_token":token,
        "companyCode":(new parent.window._user()).getData('venderCode'), //厂商编号
        "productCode":(new parent.window._user()).getData('productCode'),  //产品名称编号
        "modelNumber":(new parent.window._user()).getData('versionCode'),  //产品型号
        "status": $("#sellingEquip").val(),//是否卖出
        "runningStatus":$("#isitOnline").val(),//是否在线
        "saleRegion":$("#theZone").val(),//销售地区
        "storeRegion":$("#theZoneDepot").val(),//仓库地区
         "outStartTime":$("#outStartTime").val(),//卖出起始时间
         "outEndTime":$("#outEndTime").val(),//卖出结束时间
        "imei":$("input:text[name='imeiNum']").val()

    };
    layui.use(['table','laydate','form','laypage','layer'], function() {
        var table = layui.table//表格
            ,laydate = layui.laydate //日期
            ,laypage = layui.laypage //分页
            ,form = layui.form//表单
			,form3 = layui.form
            ,layerTips = parent.layer === undefined ? layui.layer : parent.layer
            ,$ = layui.jquery
            , layer = layui.layer; //独立版的layer无需执行这一句

        //加载图形数据
        $.ajax({
            //几个参数需要注意一下
            type: "GET",//方法类型
            async: true, // 使用异步方式
            data: {"_token":token,
                "companyCode":(new parent.window._user()).getData('venderCode'), //厂商编号
                "productCode":(new parent.window._user()).getData('productCode'),  //产品名称编号
                "modelNumber":(new parent.window._user()).getData('versionCode') //产品型号
			},
            dataType: "json",//预期服务器返回的数据类型
            url: "/store/diviceNum" ,//url
            success: function (result) {
                if(result.data!=null){
                    var count=result.data;
                    $("#deviceAllp").html(count.allDevice);
                    $("#saleCount").html(count.deviceOut);
                    $("#todaySale").html(count.deviceTodayOut);
                    $("#onlinNow").html(count.deviceOnline);

                }else {
                    alert("数据异常！");
				}
                    form.render()
            },
            error : function() {
                layer.msg("网络异常!");
            }
        });


        //初始化城市查询下拉列表
        $.ajax({
            //几个参数需要注意一下
            type: "GET",//方法类型
            async: true, // 使用异步方式
            data: {"_token":token},
            dataType: "json",//预期服务器返回的数据类型
            url: "/province/selectProvince" ,//url
            success: function (result) {
                var data=result.data;
                if (result.status == 1) {
                    var htmlStr='';
                    $.each(data,function(index,value){
                        htmlStr+= '<option value="' + value.prvId + '">' + value.prvSname + '</option>';
                    })
                    $("select[name=theZone]").append(htmlStr);
                    form.render()
                }else{
                    layer.msg(result.msg);
                }
            },
            error : function() {
                layer.msg("网络异常!");
            }
        });
        //初始化仓库下拉列表
        $.ajax({
            //几个参数需要注意一下
            type: "GET",//方法类型
            async: true, // 使用异步方式
            data: {"_token":token},
            dataType: "json",//预期服务器返回的数据类型
            url: "/dictionary/store" ,//url
            success: function (result) {
                var data=result.data;
                if (result.status == 1) {
                    var htmlStr='';
                    $.each(data,function(index,value){
                        htmlStr+= '<option value="' + value.dictId + '">' + value.dictName + '</option>';
                    })
                    $("select[name=theZoneDepot]").append(htmlStr);
                    form.render()
                }else{
                    layer.msg(result.msg);
                }
            },
            error : function() {
                layer.msg("网络异常!");
            }
        });
        //查询方法
        form.on('submit(selectDevice)', function(data){
            where={
                "_token":token,
                "companyCode":(new parent.window._user()).getData('venderCode'), //厂商编号
                "productCode":(new parent.window._user()).getData('productCode'),  //产品名称编号
                "modelNumber":(new parent.window._user()).getData('versionCode'),  //产品型号
                "status": $("#sellingEquip").val(),//是否卖出
                // "runningStatus":$("#isitOnline").val(),//是否在线
                "saleRegion":$("#theZone").val(),//销售地区
                "storeRegion":$("#theZoneDepot").val(),//仓库地区
                "outStartTime":$("#outStartTime").val(),//卖出起始时间
                "outEndTime":$("#outEndTime").val(),//卖出结束时间
                "imei":$("input:text[name='imeiNum']").val()
            }
            $.extend( where, data.field );
            table.reload('devicetable', {
                where: where
                ,page: {
                    curr: 1 //重新从第 1 页开始
                }});
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
        //表格
        table.render({
            elem: '#devicetable'
            ,url: '/store/deviceList'
            ,page: true // 是否开启分页
            ,limit : 10
            ,method: 'get'					// 请求类型 默认get
            ,where: {						// 请求的其他参数(除开page和limit)
                "_token":token,
                "companyCode":(new parent.window._user()).getData('venderCode'), //厂商编号
                "productCode":(new parent.window._user()).getData('productCode'),  //产品名称编号
                "modelNumber":(new parent.window._user()).getData('versionCode')  //产品型号
                //"status": $("#sellingEquip").val(),//是否卖出
                // "runningStatus":$("#isitOnline").val(),//是否在线
                // "saleRegion":$("#theZone").val(),//销售地区
                // "storeRegion":$("#theZone").val(),//仓库地区
                // "outStartTime":$("input:text[name='test']").val(),//卖出起始时间
                // "outEndTime":$("input:text[name='test']").val(),//卖出结束时间
                //"imei":$("input:text[name='imeiNum']").val()

            }
            ,cols: [
                [{
                    field: 'imei',
                    width: 80,
                    title: 'IMEI号码'
                }, {
                    field: 'outTime',
                    width: 80,
                    title: '卖出时间'
                }, {
                    field: 'saleRegionName',
                    width: 80,
                    title: '销售所在地',
                    sort: true
                },{
                    field: 'storeRegionName',
                    width: 80,
                    title: '库存所在地',
                    sort: true
                }, {
                    field: 'onlineTime',
                    width: 80,
                    title: '在线时长'
                }, {
                    field: 'latelyLoginTime',
                    width: 219,
                    title: '最近上线时间'
                }, {
                    field: 'runningStatus',
                    width: 80,
                    title: '运行状态'
                }, {
                    field: 'isRun',
                    width: 80,
                    title: '启停状态',
					template:function (d) {
                        if(d.isRun=='0'){
                            return "停用";
                        }else {
                            return "启用";
                        }
                    }
                }, {
                    field: 'status',
                    width: 80,
                    title: '是否卖出'
                }, {
                    align: 'center',
                    width: 178,
                    title: '操作',
                    toolbar: '#barDemo'
                }],
            ],
            done : function(res, curr, count){

                $("[data-field='isRun']").children().each(function(){
                    if($(this).text()=='0'){
                        $(this).text("启用")
                    }else if($(this).text()=='1'){
                        $(this).text("停用")
                    }
                });
                    $("[data-field='status']").children().each(function(){
                        if($(this).text()=='1'){
                            $(this).text("已卖出");
                            // $().text("已卖出");
                        }else if($(this).text()=='0'){
                            $(this).text("未卖出")
                        }
                    })
                    ,
                    $("[data-field='runningStatus']").children().each(function(){
                        if($(this).text()=='1'){
                            $(this).text("离线");
                            // $().text("已卖出");
                        }else if($(this).text()=='0'){
                            $(this).text("在线")
                        }
                    })


            },

        });

        //监听工具条
        table.on('tool(devicetable)', function(obj) {
            var _this = $(this);
            var layEvent = obj.event;
            var data = obj.data;
		// console.log(d.isValid)
            // if(obj.event === 'detail') {
            //     layer.msg('ID：' + data.id + ' 的查看操作');
            // } else if(obj.event === 'del') {
            //     layer.confirm('真的删除行么', function(index) {
            //         obj.del();
            //         layer.close(index);
            //     });
            // } else
                if(layEvent === 'edit') {
                showform(obj,"edit")
            }else if(layEvent === 'stop'){
					layer.confirm('你确定要停用该资源吗？', {
						btn: ['确定','关闭'] // 按钮
					},
                        function(){
                            $.ajax({
                                url:  '/store/update',
                                type: 'post',
                                dataType: 'json',
                                data:{
                                    '_token':token,
                                    'id' : data.id,
									'isRun':'0'
                                }
                            }).done(function(res) {
								if(res.status == 1){
                                    layer.msg('停用成功');
                                    table.reload('devicetable', {
                                        where: where
                                        ,page: {
                                            curr: 1 //重新从第 1 页开始
                                        }});
								}else{
                                    layer.msg(res.msg);
								}

                            });
                        }
					);
			}else if(layEvent === 'open'){
                    layer.confirm('你确定要启用该资源吗？', {
                        btn: ['确定','关闭'] // 按钮
                    },
                        function(){
                            $.ajax({
                                url:  '/store/update',
                                type: 'post',
                                dataType: 'json',
                                data:{
                                    '_token':token,
                                    'id' : data.id,
                                    'isRun':'1'
                                }
                            }).done(function(res) {
                                if(res.status == 1){
                                    layer.msg('启用成功');

                                    table.reload('devicetable', {
                                        where: where
                                        ,page: {
                                            curr: 1 //重新从第 1 页开始
                                        }});

								}else{
                                    layer.msg(res.msg);
								}


                            });
                        }
					);
			}
        });

        function showform(formData,event){

            //判断是否已弹出表单
            // if(document.getElementById("formDiv")){
            //     return;
            // }

            $.get('terminal-form.html',function(formData){
                addBoxIndex = layer.open({
					type:1,
					title:"编辑终端设备",
					content:formData,
                    btn:["保存","取消"],
					shade:false,
                    offset: ['80px', '15%'],
                    area: ['800px', '290px'],
                    zIndex: 999,
                    maxmin: true,
                    yes: function(index) {
                        //触发表单的提交事件
                        $('form.layui-form').find('button[lay-filter=edit]').click();
                    },
                    full: function(elem) {
                        var win = window.top === window.self ? window : parent.window;
                        $(win).on('resize', function() {
                            var $this = $(this);
                            elem.width($this.width()).height($this.height()).css({
                                top: 0,
                                left: 0
                            });
                            elem.children('div.layui-layer-content').height($this.height() - 95);
                        });
                    },
                    success: function() {

                        // var form3 = layui.form;
                        // form3.render();
                        // var laydate = layui.laydate //日期
                        laydate.render({
                            elem: '#sallTime'
                            ,type: 'datetime'
                        });
                        // console.log(form3)
                        form.on('submit(edit)', function(data) {
                            $.ajax({
                                //几个参数需要注意一下
                                type: "POST",//方法类型
                                async: false, // 使用同步方式
                                // data:  ,//cc的data
                                dataType: "json",//预期服务器返回的数据类型
                                // url: '' ,//cc的url
                                yes: function(index) {
                                    //触发表单的提交事件
                                    $('form.layui-form').find('button[lay-filter=edit]').click();
                                },
                                full: function(elem) {
                                    var win = window.top === window.self ? window : parent.window;
                                    $(win).on('resize', function() {
                                        var $this = $(this);
                                        elem.width($this.width()).height($this.height()).css({
                                            top: 0,
                                            left: 0
                                        });
                                        elem.children('div.layui-layer-content').height($this.height() - 95);
                                    });
                                },
                                success: function (result) {
                                    var data=result.data;
                                    if (result.status == 1) {
                                        layer.closeAll()
                                        table.reload('dataTable', {
                                            where: where
                                            ,page: {
                                                curr: 1 //重新从第 1 页开始
                                            }});
                                    }else{
                                        layer.msg(result.msg);
                                    }
                                },
                                error : function() {
                                    layer.msg("网络异常!");
                                }
                            });

                            //这里可以写ajax方法提交表单
                            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                        });

					}

				})
			})
		}


        //处理状态列
        $("[data-field='isValid']").children().each(function(){
            if($(this).text()=='0'){
                $(this).text("停用")
            }else if($(this).text()=='1'){
                $(this).text("启用")
            }
        });




        //分页
        /*laypage.render({
            elem: '#test' //分页容器的id
            ,count: 5 //总页数
            ,loading: true
            ,limit: 2 //每页默认显示的数量
            ,done:function(res){
                console.log(res)
                userPage.data = res.data;
            }
//			    ,skin: '#1E9FFF' //自定义选中色值
            //,skip: true //开启跳页
//			    ,jump: function(obj, first){
//			      if(!first){
//			        layer.msg('第'+ obj.curr +'页');
//			      }
//			    }
        });*/

//				var $ = layui.$,
//					active = {
//						getCheckData: function() { //获取选中数据
//							var checkStatus = table.checkStatus('idTest'),
//								data = checkStatus.data;
//							layer.alert(JSON.stringify(data));
//						},
//						getCheckLength: function() { //获取选中数目
//							var checkStatus = table.checkStatus('idTest'),
//								data = checkStatus.data;
//							layer.msg('选中了：' + data.length + ' 个');
//						},
//						isAll: function() { //验证是否全选
//							var checkStatus = table.checkStatus('idTest');
//							layer.msg(checkStatus.isAll ? '全选' : '未全选')
//						}
//					};

//				$('.demoTable .layui-btn').on('click', function() {
//					var type = $(this).data('type');
//					active[type] ? active[type].call(this) : '';
//				});

        //日期时间选择器
        laydate.render({
            elem: '#startTime'
            ,type: 'datetime'
        });
        laydate.render({
            elem: '#endTime'
            ,type: 'datetime'
        });
        //但是，如果你的HTML是动态生成的，自动渲染就会失效
        //因此你需要在相应的地方，执行下述方法来手动渲染，跟这类似的还有 element.init();
        //form.render();

        $('#layerDemo .layui-btn').on('click', function(){
            var othis = $(this), method = othis.data('method');
            active[method] ? active[method].call(this, othis) : '';
        });
    });

</script>
</body>
</html>
